﻿using Autofac;
using IdentityModel.Client;
using Sayook.Framework.AutoLibrary;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace Sayook.Framework.Template.Client
{
    internal class Program
    {
        private static async Task Main()
        {
            var s = 0;

            var autofacManager = new AutofacManager();
            var builder = new ContainerBuilder();
            autofacManager.SetContainer(builder.Build());

            while (s != 99)
            {
                // discover endpoints from metadata
                var client = new HttpClient();

                var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5000");
                if (disco.IsError)
                {
                    Console.WriteLine(disco.Error);
                    continue;
                }

                // request token
                var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
                {
                    Address = disco.TokenEndpoint,
                    ClientId = "client",
                    ClientSecret = "123456",

                    Scope = "TemplateApi"
                });

                if (tokenResponse.IsError)
                {
                    Console.WriteLine(tokenResponse.Error);
                    continue;
                }

                Console.WriteLine(tokenResponse.Json);
                Console.WriteLine("\n\n");

                // call api
                var apiClient = new HttpClient();
                apiClient.SetBearerToken(tokenResponse.AccessToken);

                var response = await apiClient.GetAsync("http://localhost:8080/test/get");
                if (!response.IsSuccessStatusCode)
                {
                    Console.WriteLine(response.StatusCode);
                }
                else
                {
                    var content = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(content);
                }
                s = int.Parse(Console.ReadLine());
            }
            Console.WriteLine("Out...");
        }
    }
}